﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.ModelBinding;

using ERPStore.Extensions;
using ERPStore.Web.Extensions;
using ERPStore.Offers.Repositories;

using CloudSoft.Extensions;

namespace ERPStore.Offers.Controllers
{
	public class AdminOffersApiController : ApiController
	{
		public AdminOffersApiController(Services.AdminOffersService offersService)
		{
			AdminOffersService = offersService;
		}

		protected Services.AdminOffersService AdminOffersService { get; private set; }

		[HttpGet]
		public DateTime Ping()
		{
			return DateTime.Now;
		}

		[HttpGet]
		[ERPStore.Web.Controllers.ActionFilters.ApiAuthorizedOperation]
		public bool RefreshAllOffers()
		{
			AdminOffersService.RefreshAllOffers();
			return true;
		}

		/// <summary>
		/// Creation d'une offre
		/// </summary>
		/// <returns></returns>
		[ERPStore.Web.Controllers.ActionFilters.ApiAuthorizedOperation]
		[HttpGet]
		public Models.OfferEx CreateOffer()
		{
			var offer = AdminOffersService.CreateOffer();
			return offer;
		}

		[ERPStore.Web.Controllers.ActionFilters.ApiAuthorizedOperation]
		[HttpPost]
		public List<ERPStore.Models.BrokenRule> ValidateOffer(Models.OfferEx offer)
		{
			var result = AdminOffersService.ValidateOffer(offer);
			return result;
		}

		[ERPStore.Web.Controllers.ActionFilters.ApiAuthorizedOperation]
		[HttpPost]
		[HttpPut]
		public Models.OfferEx SaveOffer(Models.OfferEx offer)
		{
			try
			{
				AdminOffersService.SaveOffer(offer);
			}
			catch (ERPStore.Models.ValidationException vex)
			{
				var httpResponse = new HttpResponseMessage(System.Net.HttpStatusCode.Gone);
				httpResponse.Content = vex.ToContent();
				httpResponse.ReasonPhrase = "Validation Errors";
				throw new HttpResponseException(httpResponse);
			}
			catch (Exception ex)
			{
				var httpResponse = new HttpResponseMessage(System.Net.HttpStatusCode.ExpectationFailed);
				httpResponse.Content = new StringContent(ex.ToString() + "\r\n" + "Model : " + offer.ToJSon());
				throw new HttpResponseException(httpResponse);
			}
			return offer;
		}

		[ERPStore.Web.Controllers.ActionFilters.ApiAuthorizedOperation]
		[HttpGet]
		public IQueryable<Models.OfferEx> GetOffers()
		{
			return AdminOffersService.GetAllOffers();
		}

		[ERPStore.Web.Controllers.ActionFilters.ApiAuthorizedOperation]
		[HttpPost]
		[HttpGet]
		public Models.OfferListResult GetOfferList(Models.OfferListFilter filter)
		{
			var result = new Models.OfferListResult();
			var query = AdminOffersService.GetAllOffers();

			if (!filter.SearchTerm.IsNullOrTrimmedEmpty())
			{
				query = query.Where(i => i.Name.IndexOf(filter.SearchTerm) != -1);
			}

			if (filter.IsActive.HasValue)
			{
				query = query.Where(i => i.EndDate.GetValueOrDefault(DateTime.MaxValue) >= DateTime.Now);
			}
			
			result.TotalCount = query.Count();

			if (!filter.SortByPropertyName.IsNullOrTrimmedEmpty())
			{
				if (filter.SortDirection == System.ComponentModel.ListSortDirection.Ascending)
				{
					query = query.OrderBy(filter.SortByPropertyName);
				}
				else
				{
					query = query.OrderByDescending(filter.SortByPropertyName);
				}
			}
			else
			{
				query = query.OrderByDescending(i => i.Id);
			}

			query = query.Skip(filter.PageIndex * filter.PageSize).Take(filter.PageSize);

			result.List = query.ToList();
			return result;
		}

		[ERPStore.Web.Controllers.ActionFilters.ApiAuthorizedOperation]
		[HttpGet]
		public IEnumerable<Models.OfferedProduct> GetOfferedProductList(int id)
		{
			var offer = AdminOffersService.GetOfferById(id);
			if (offer != null)
			{
				return AdminOffersService.GetOfferedProductListByOfferId(offer.Id);
			}
			return new List<Models.OfferedProduct>();
		}

		[ERPStore.Web.Controllers.ActionFilters.ApiAuthorizedOperation]
		[HttpGet]
		public Models.OfferedProduct CreateOfferedProduct()
		{
			var result = AdminOffersService.CreateOfferedProduct();
			return result;
		}

		[ERPStore.Web.Controllers.ActionFilters.ApiAuthorizedOperation]
		[HttpGet]
		[HttpPost]
		public IEnumerable<ERPStore.Models.BrokenRule> ValidateOfferedProduct(Models.OfferedProduct offeredProduct)
		{
			var result = AdminOffersService.ValidateOfferedProduct(offeredProduct);
			return result;
		}

		[ERPStore.Web.Controllers.ActionFilters.ApiAuthorizedOperation]
		[HttpPost]
		[HttpPut]
		public Models.OfferedProduct SaveOfferedProduct(Models.OfferedProduct offeredProduct)
		{
			try
			{
				AdminOffersService.SaveOfferedProduct(offeredProduct);
			}
			catch (ERPStore.Models.ValidationException vex)
			{
				var httpResponse = new HttpResponseMessage(System.Net.HttpStatusCode.Gone);
				httpResponse.Content = vex.ToContent();
				throw new HttpResponseException(httpResponse);
			}
			catch(Exception ex)
			{
				var httpResponse = new HttpResponseMessage(System.Net.HttpStatusCode.Gone);
				httpResponse.Content = new StringContent(ex.ToString());
				throw new HttpResponseException(httpResponse);
			}
			return offeredProduct;
		}

		[ERPStore.Web.Controllers.ActionFilters.ApiAuthorizedOperation]
		[HttpPost]
		[HttpDelete]
		public bool DeleteOffer(int id)
		{
			var offer = AdminOffersService.GetOfferById(id);
			var result = false;
			if (offer == null)
			{
				return result;
			}
			try
			{
				AdminOffersService.DeleteOffer(offer);
				result = true;
			}
			catch (Exception ex)
			{
				var httpResponse = new HttpResponseMessage(System.Net.HttpStatusCode.ExpectationFailed);
				httpResponse.Content = new StringContent(ex.ToString());
				throw new HttpResponseException(httpResponse);
			}
			return result;
		}

		[ERPStore.Web.Controllers.ActionFilters.ApiAuthorizedOperation]
		[HttpPost]
		[HttpDelete]
		public bool DeleteOfferedProduct(int id)
		{
			var offeredProduct = AdminOffersService.GetOfferedProductById(id);
			var result = false;
			if (offeredProduct == null)
			{
				return result;
			}
			try
			{
				AdminOffersService.DeleteOfferedProduct(offeredProduct);
				result = true;
			}
			catch(Exception ex)
			{
				var httpREsponse = new HttpResponseMessage(System.Net.HttpStatusCode.ExpectationFailed);
				httpREsponse.Content = new StringContent(ex.ToString());
				throw new HttpResponseException(httpREsponse);;
			}
			return result;
		}

		[ERPStore.Web.Controllers.ActionFilters.ApiAuthorizedOperation]
		public IEnumerable<Models.OfferedProduct> GetOfferListByProduct(int id)
		{
			var list = AdminOffersService.GetCurrentOffers().Where(i => i.ProductList.Any(p => p.ProductId == id));
			var result = new List<Models.OfferedProduct>();
			foreach (var item in list)
			{
				var offeredProduct = item.ProductList.FirstOrDefault(i => i.ProductId == id);
				result.Add(offeredProduct);
			}
			return result;
		}
	}
}